package com.qqt.csr.common.vo.resp;

import com.google.common.collect.Lists;
import com.qqt.csr.common.exception.StatusCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页响应对象
 *
 */
@Getter
@Setter
@Schema(description = "分页请求响应对象")
public class PageResponse<T> extends BaseResponse implements Serializable {
	private static final long serialVersionUID = 1L;

	@Schema(description = "响应数据")
	TableData<T> data;

	@SuppressWarnings("unchecked")
	public PageResponse() {
		this.data = new TableData<T>(0L,  Lists.newArrayList());
	}

	public static <T> PageResponse<T> common(int code, String message, TableData<T> table) {
		PageResponse<T> result = new PageResponse<>();
		result.setCode(code);
		result.setData(table);
		result.setMessage(message);
		return result;
	}

	public PageResponse(List<T> records, Long total) {
		this.data = new TableData<T>(total, records);
	}

	public PageResponse(Long total, Long pageSize, Long page, List<T> records) {
		this.data = new TableData<T>(total, page, pageSize , records);
	}

	public PageResponse<T> code(StatusCode code) {
		this.setCode(code.getCode());
		this.setMessage(code.getMessage());
		return this;
	}

	public PageResponse<T> message(String message) {
		this.setMessage(message);
		return this;
	}

	public PageResponse<T> total(Long total) {
		data.setTotal(total);
		return this;
	}

	public PageResponse<T> page(Long page) {
		data.setPage(page);
		return this;
	}

	public PageResponse<T> size(Long pageSize) {
		data.setPageSize(pageSize);
		return this;
	}

	public PageResponse<T> totalPage(Long totalPage) {
		data.setTotalPage(totalPage);
		return this;
	}

	public PageResponse<T> records(List<T> records) {
		data.setList(records);
		return this;
	}

	@Getter
	@Setter
	public static class TableData<T> implements Serializable{

		private static final long serialVersionUID = 2503014434286154647L;

		public TableData() {
		}

		@Schema(description = "数据集", required = true)
		private List<T> list = new ArrayList<>();
		@Schema(description = "当前页数", required = true)
		private Long page;
		@Schema(description = "每页条数", required = true)
		private Long pageSize = 10L;
		@Schema(description = "总数", required = true)
		private Long total;
		@Schema(description = "总页数", required = true)
		private Long totalPage;

		public TableData(Long total, List<T> records) {
			this.total = total;
			this.list = records;
		}

		public TableData(Long total, Long current, Long size, List<T> records) {
			this.list = records;
			this.page = current;
			this.pageSize = size;
			this.total = total;
		}

		public long getTotalPage() {
			totalPage = 0L;
			if (pageSize > 0) {
				if (total % pageSize == 0) {
					totalPage = total / pageSize;
				} else {
					totalPage = total / pageSize + 1;
				}
			}
			return totalPage;

		}

	}

}
